package com.easy.service.impl;

import com.easy.bean.UserAccount;
import com.easy.mapper.UserAccountDao;
import com.easy.service.LoginService;
import com.easy.util.PasswordUtil;
import com.easy.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserAccountDao userAccountDao;

    @Override
    public String login(UserAccount userAccount) {
        System.out.println("=== 开始登录验证过程 ===");
        System.out.println("用户名: " + userAccount.getUsername());

        // 查询数据库
        UserAccount result = userAccountDao.getByAccount(userAccount.getUsername());
        System.out.println("数据库查询结果: " + (result != null ? "找到用户" : "未找到用户"));

        if (result == null) {
            throw new RuntimeException("用户名或密码错误");
        }

        // 验证密码（不更新数据库）
        boolean passwordMatch = PasswordUtil.checkPassword(userAccount.getPassword(), result.getPassword_hash());
        System.out.println("加密密码验证结果: " + passwordMatch);

        if (!passwordMatch) {
            throw new RuntimeException("用户名或密码错误");
        }

        System.out.println("密码验证成功");
        System.out.println("=== 登录验证过程结束 ===");
        return TokenUtil.genToken(result);
    }

    @Override
    public UserAccount register(UserAccount userAccount) {
        // 检查用户名
        if (userAccountDao.getByAccount(userAccount.getUsername()) != null) {
            throw new RuntimeException("用户名已存在");
        }

        // 检查邮箱
        if (userAccount.getEmail() != null && !userAccount.getEmail().isEmpty()) {
            if (userAccountDao.getByEmail(userAccount.getEmail()) != null) {
                throw new RuntimeException("邮箱已被注册");
            }
        }

        // 密码加密写入数据库
        String encryptedPassword = PasswordUtil.encryptPassword(userAccount.getPassword());
        userAccount.setPassword_hash(encryptedPassword);
        userAccount.setPassword(null);

        userAccountDao.add(userAccount);

        UserAccount registeredUser = userAccountDao.one(userAccount.getId());
        registeredUser.setPassword_hash(null);
        return registeredUser;
    }
}